import {router,addRoutes} from "./router";
import mockRoutes from "./router/mockRoutes";

import cookies from "./utils/auth";
import messageInfo from "./utils/message";
import store from "./store";
import progress from "@/utils/nprogress";

//防止重复性获取userInfo数据（频繁请求接口）
let needGetInfo=false

//全局路由-前置守卫
router.beforeEach(async (to, from, next) => {
  progress.start()
  console.log("to: ",to,"from: ",from,"next: ",next);
 
  const userInfo=LocalStorage.get("userInfo")
  if(userInfo){
    store.commit('setUserInfo', userInfo)
  }
  const token=cookies.getToken()
  // console.log("token: ",token,!token)
  // console.log("userInfo: ",userInfo)
  // console.log("to: ",to.path)

  //是否有新路由注册
  let newRoute=false

  //未登录跳转登录
  if((!token || token==undefined) && to.path != '/login'){
    // console.log("未登录")
    messageInfo.notific.error("请先登录")
    return next(
      {
        path: '/login'
      }
    )
  }else{
    //更新mutations
    if(!needGetInfo){
      let userInfo= await store.dispatch("getUserInfo")
      console.log("permission-userInfo: ",userInfo)
      needGetInfo=true
      //获取到用户数据后，更新动态路由TODO，这里先指向router.js定义好的路由
      if(userInfo?.menuList.length>0){
        newRoute= addRoutes(userInfo?.menuList)
      }else{
        newRoute= addRoutes(mockRoutes)
      }
    }
    
    
  }
  // //防止重复登录
  if(token && to.path == '/login'){
    messageInfo.notific.error("请勿重复登录")
    return next(
      {
        path: from.path?from.path:"/"
      }
    )
  }
  console.log("newRoute-------------: ", newRoute)
  
  //更新页面标题
  let title=to.meta.title?to.meta.title+'-Cevent后台管理系统':"Cevent后台管理系统";
  document.title=title;
  //执行跳转，更新动态路由，指定路由
  newRoute? next(to.fullPath) : next()
});

//全局路由-后置守卫
router.afterEach((to,from)=>{
  // console.log("after------to: ",to,"from: ",from)
  progress.end()
})

